﻿using CSRedis;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;

namespace AdvancedApi.Models
{
    public class RedisConfigurationSource : IConfigurationSource
    {
        public readonly RedisConfigurationOptions _options;

        public RedisConfigurationSource(RedisConfigurationOptions options)
        {
            _options = options;
        }

        public IConfigurationProvider Build(IConfigurationBuilder builder)
        {
            return new RedisConfigurationProvider(_options);
        }
    }
    public class RedisConfigurationProvider : ConfigurationProvider
    {
        public CSRedisClient _redisClient;
        public readonly RedisConfigurationOptions _options;

        public RedisConfigurationProvider(RedisConfigurationOptions options)
        {
            _options = options;
            _redisClient = new CSRedisClient(_options.ConnectionString);
            if (options.AutoReload)
            {
                //利用Redis的发布-订阅重新加载配置
                _redisClient.Subscribe((_options.HashCacheChannel, msg => Load()));
            }
        }

        public override void Load()
        {
            Data = _redisClient.HGetAll<string>(_options.HashCacheKey) ?? new Dictionary<string, string>();
        }
    }

    public static class RedisConfigurationExtensions
    {
        public static IConfigurationBuilder AddRedisConfiguration(this IConfigurationBuilder builder, RedisConfigurationOptions options)
        {
            return builder.Add(new RedisConfigurationSource(options));
        }
    }
}
